package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService service;
    @Override
    public void save(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public void update(BpmnInfo BpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(BpmnInfo);
    }

    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }




    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            bpmnInfoMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }
    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
//        if (qo.getName()!=null && qo.getName()!="") {
//            qo.setName(qo.getName().substring(0, qo.getName().lastIndexOf(",")));
//        }
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        List<BpmnInfo> bpmnInfos = bpmnInfoMapper.selectForList(qo);
        return new TablePageInfo<BpmnInfo>(bpmnInfos);
    }

    @Override
    @Transactional
    public void deploy(MultipartFile multipartFile, String bpmnType, String bpmnLabel, String info) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        String name = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        if (!"bpmn".equalsIgnoreCase(name)) {
            throw new BusinessException("请上传bpmn类型的文件");
        }
        //进行部署
        Deployment deployment = repositoryService.createDeployment().addInputStream(originalFilename, multipartFile.getInputStream()).deploy();
        //获取部署对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setBpmnLabel(bpmnLabel);
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setProcessDefinitionKey(processDefinition.getKey());
        bpmnInfo.setDeployTime(new Date());
        bpmnInfo.setVersion(processDefinition.getVersion());
        bpmnInfo.setInfo(info);
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    @Transactional
    public void delete(Long ids) {
        // 根据id 获取bpmnInfo 对象
        BpmnInfo bpmnInfo = this.get(ids);
        String key = bpmnInfo.getProcessDefinitionKey();
        Integer version = bpmnInfo.getVersion();
        String deploymentId=null;
        //查看当前流程定义有哪些流程实例
        List<ProcessInstance> list = service.createProcessInstanceQuery().processDefinitionKey(key).list();
        //找多所有业务的业务标识,通过业务标识更新对应的状态
        for (ProcessInstance processInstance : list) {
            String businessKey = processInstance.getBusinessKey();
            //TODO
        }
        //判断 实例对象中是否长度大于0 如果大于0 就直接从实例对象中获取 deploymentId  否者就根据版本号 和 key 直接查询
        if (list.size()>0){
            deploymentId=list.get(0).getDeploymentId();
        }else {
            //获取流程定义
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionVersion(version).processDefinitionKey(key).singleResult();
            deploymentId=processDefinition.getDeploymentId();
        }
        //删除定义
        repositoryService.deleteDeployment(deploymentId,true);
        bpmnInfoMapper.deleteByPrimaryKey(ids);

    }

    @Override
    public InputStream readResource(Long id, String type) {
//        //通过bpmninfo 获取到流程定义的key
//        BpmnInfo bpmnInfo = this.get(id);
//        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
//                .processDefinitionKey(bpmnInfo.getProcessDefinitionKey())
//                .processDefinitionVersion(bpmnInfo.getVersion())
//                .singleResult();
//        String resourceName = processDefinition.getResourceName();
//        String deploymentId = processDefinition.getDeploymentId();
//        if (type.equalsIgnoreCase("xml")) {
//      return repositoryService.getResourceAsStream(deploymentId,resourceName);
//        }else {
//            //流程图的模型对象
//            BpmnModel model = repositoryService.getBpmnModel(processDefinition.getId());
//            // 流程文件图片生成器
//            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
//            return generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
//        }

        BpmnInfo bpmnInfo = this.get(id);
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(bpmnInfo.getProcessDefinitionKey())
                .processDefinitionVersion(bpmnInfo.getVersion()).singleResult();
        if (type.equalsIgnoreCase("xml")){
            return repositoryService.getResourceAsStream(processDefinition.getDeploymentId(),processDefinition.getResourceName());
        }else {
            BpmnModel model=repositoryService.getBpmnModel(processDefinition.getId());
            DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            return generator.generateDiagram(model,Collections.EMPTY_LIST,Collections.EMPTY_LIST,"宋体","宋体","宋体");
        }
    }

    @Override
    public BpmnInfo getByBpmnType(String auditType) {
        return bpmnInfoMapper.getByBpmnType(auditType);
    }


}
